﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.Caching;
using PetShop.Web.Entities;

namespace PetShop.Web
{
    public partial class WebFormCategory : System.Web.UI.Page
    {
        

        protected void PageChanged(object sender, DataGridPageChangedEventArgs e)
        {

            products.CurrentPageIndex = e.NewPageIndex;

          
            string categoryKey = WebComponents.CleanString.InputText(Request["categoryId"], 50);



            if (string.IsNullOrEmpty(categoryKey))
                return ;

        
            if (Cache[categoryKey] != null)
            {
             
                products.DataSource = (List<ProductInfo>)Cache[categoryKey];
            }
            else
            {

                List<ProductInfo> productsByCategory = new List<ProductInfo>();



                using (SqlCommand cmd = new SqlCommand())
                {
                    using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["SQLConnString"]))
                    {
                        cmd.Connection = conn;
                        cmd.CommandText = "SELECT ProductId, Name FROM Product WHERE Category = @Category";
                        cmd.CommandType = CommandType.Text;
                        SqlParameter parm = new SqlParameter("@Category", SqlDbType.Char, 10);
                        parm.Value = categoryKey;
                        cmd.Parameters.Add(parm);
                        conn.Open();
                        using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (rdr.Read())
                            {
                                ProductInfo product = new ProductInfo(rdr.GetString(0), rdr.GetString(1), null);
                                productsByCategory.Add(product);
                            }
                        }
                    }
                }

                Cache.Add(categoryKey, productsByCategory, null, DateTime.Now.AddHours(12), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
                products.DataSource = productsByCategory;
            }

            products.DataBind();
            lblPage.Text = categoryKey;
        }




    
    }
}
